/************************************************************************
*************************************************************************
@Name :       	jRating - jQuery Plugin
@Revison :    	3.0
@Date : 		28/01/2013 
@Author:     	 ALPIXEL - (www.myjqueryplugins.com - www.alpixel.fr) 
@License :		 Open Source - MIT License : http://www.opensource.org/licenses/mit-license.php
 
**************************************************************************
*************************************************************************/
var tclWidget = tclWidget || {};
(function(tclWidget, $) {
	tclWidget.$.fn.jRating = function(op) {
		var defaults = {
			/** String vars **/
			bigStarsPath : 'https://googledrive.com/host/0B6cA825-pUVbbHplZG9nOWZQd00/plugins/jRating/icons/stars.png', // path of the icon stars.png
			smallStarsPath : 'https://googledrive.com/host/0B6cA825-pUVbbHplZG9nOWZQd00/plugins/jRating/icons/small.png', // path of the icon small.png
			phpPath : 'https://googledrive.com/host/0B6cA825-pUVbbHplZG9nOWZQd00/plugins/jRating/php/jRating.php?callback=?', // path of the php file jRating.php
            scriptPath : 'https://script.google.com/macros/s/AKfycbxFAYxEiE5anRwcY3n3TwRwHKO4OXFvuSt-a8EcHt4kAROd1Yk/exec?prefix=?', // path to GoogleScriptAPI RatingAPI; use 'prefix=?' instead of callback=?
            // ver.27:  https://script.google.com/macros/s/AKfycbxFAYxEiE5anRwcY3n3TwRwHKO4OXFvuSt-a8EcHt4kAROd1Yk/exec
            // ver.26:  https://script.google.com/macros/s/AKfycbxFAYxEiE5anRwcY3n3TwRwHKO4OXFvuSt-a8EcHt4kAROd1Yk/exec
			type : 'big', // can be set to 'small' or 'big'

			/** Boolean vars **/
			step:false, // if true,  mouseover binded star by star,
			isDisabled:false,
			showRateInfo: true,
			canRateAgain : true,

			/** Integer vars **/
			length:5, // number of star to display
			decimalLength : 1, // number of decimals.. Max 3, but you can complete the function 'getNote'
			rateMax : 10, // maximal rate - integer from 0 to 9999 (or more)
			rateInfosX : -45, // relative position in X axis of the info box when mouseover
			rateInfosY : 5, // relative position in Y axis of the info box when mouseover
			nbRates : 0,

			/** Functions **/
			onSuccess : function(data){
                            //tclWidget.$(element).parent().next('.rateBox').find('.rateBoxScore').text(data.rate);
                            tclWidget.$('#tclUserRating').text((data.rate || "- -"));
                            tclWidget.$('#tclSiteRating').text((data.siteRate || "- -"));
                            //tclWidget.$(element).next('.ratingUser').text(data.votes + ' votes');
                            tclWidget.$('#tclUserVotes').text(data.votes + ' user rating(s)');
                        },
			onError : null,
		}; 

		if(this.length>0)
		return this.each(function() {
			/*vars*/
			var opts = tclWidget.$.extend(defaults, op),    
			newWidth = 0,
			starWidth = 0,
			starHeight = 0,
			bgPath = '',
			hasRated = false,
			globalWidth = 0,
			nbOfRates = opts.nbRates;

			getStarWidth();
			tclWidget.$(this).height(starHeight);

			var average = parseFloat(tclWidget.$(this).attr('data-average')), // get the average of all rates
			idBox = parseInt(tclWidget.$(this).attr('data-id')), // get the id of the box
			widthRatingContainer = starWidth*opts.length, // Width of the Container
			widthColor = average/opts.rateMax*widthRatingContainer, // Width of the color Container
                        disableBox = (tclWidget.$(this).attr('data-isDisabled')) === "true",
                        idPost = tclWidget.$(this).attr('data-pid'),
                        titlePost = tclWidget.$(this).attr('data-ptitle'),
                        timePost = String(tclWidget.$(this).attr('data-ptime')),
                        timePost = timePost.split(', '),
                        timePost = timePost[1].trim() + ', ' + timePost[2].trim(),
                        
			quotient = 
			tclWidget.$('<div>', 
			{
				'class' : 'jRatingColor',
				css:{
					width:widthColor
				}
			}).appendTo(tclWidget.$(this)),

			average = 
			tclWidget.$('<div>', 
			{
				'class' : 'jRatingAverage',
				css:{
					width:0,
					top:- starHeight
				}
			}).appendTo(tclWidget.$(this)),

			 jstar =
			tclWidget.$('<div>', 
			{
				'class' : 'jStar',
				css:{
					width:widthRatingContainer,
					height:starHeight,
					top:- (starHeight*2),
					background: 'url('+bgPath+') repeat-x'
				}
			}).appendTo(tclWidget.$(this));
                        //tclWidget.$.ajaxSetup({ dataType: "jsonp" });
                        /*
                        // AJAX Test -------------------------------------
                        tclWidget.$.ajax({
                            url: opts.scriptPath,
                            jsonp: "callback",
                            datatype: "jsonp",
                            data:{
                                postID : idPost,
							    postTitle: titlePost,
							    postTime: timePost,
							    action : 'getRating'
                            },
                            success:
                                function(data) {
	                                if(!data.error)
								    {
									    if(opts.onSuccess) opts.onSuccess( data );
								    }
								    else
								    {
									    if(opts.onError) opts.onError( data );
								    }
							    }
                        });
                        
                        // END AJAX Test --------------------------------
                        */
                        tclWidget.$.getJSON(opts.scriptPath,{
                                                
							postID : idPost,
							postTitle: titlePost,
							postTime: timePost,
							action : 'getRating'
						},
                            function(data) {
	                            if(!data.error)
								{
									if(opts.onSuccess) opts.onSuccess( data );
								}
								else
								{
									if(opts.onError) opts.onError( data );
								}
							}
                                           
                        );
                        
			if(tclWidget.$(this).hasClass('jDisabled') || opts.isDisabled || disableBox)
				var jDisabled = true;
			else
				var jDisabled = false;

			tclWidget.$(this).css({width: widthRatingContainer,overflow:'hidden',zIndex:1,position:'relative'});
                        

			if(!jDisabled)
			tclWidget.$(this).unbind().bind({
				mouseenter : function(e){
					var realOffsetLeft = findRealLeft(this);
					var relativeX = e.pageX - realOffsetLeft;
					if (opts.showRateInfo)
					var tooltip = 
					tclWidget.$('<p>',{
						'class' : 'jRatingInfos',
						html : getNote(relativeX)+' <span class="maxRate">/ '+opts.rateMax+'</span>',
						css : {
							top: (e.pageY + opts.rateInfosY),
							left: (e.pageX + opts.rateInfosX)
						}
					}).appendTo('body').show();
				},
				mouseover : function(e){
					tclWidget.$(this).css('cursor','pointer');	
				},
				mouseout : function(){
					tclWidget.$(this).css('cursor','default');
					if(hasRated) average.width(globalWidth);
					else average.width(0);
				},
				mousemove : function(e){
					var realOffsetLeft = findRealLeft(this);
					var relativeX = e.pageX - realOffsetLeft;
					if(opts.step) newWidth = Math.floor(relativeX/starWidth)*starWidth + starWidth;
					else newWidth = relativeX;
					average.width(newWidth);					
					if (opts.showRateInfo)
					tclWidget.$("p.jRatingInfos")
					.css({
						left: (e.pageX + opts.rateInfosX)
					})
					.html(getNote(newWidth) +' <span class="maxRate">/ '+opts.rateMax+'</span>');
				},
				mouseleave : function(){
					tclWidget.$("p.jRatingInfos").remove();
				},
				click : function(e){
                    var element = this;
					
					/*set vars*/
					hasRated = true;
					globalWidth = newWidth;
					nbOfRates--;
					
					if(!opts.canRateAgain || parseInt(nbOfRates) <= 0) tclWidget.$(this).unbind().css('cursor','default').addClass('jDisabled');
					
					if (opts.showRateInfo) tclWidget.$("p.jRatingInfos").fadeOut('fast',function(){tclWidget.$(this).remove();});
					e.preventDefault();
					var rate = getNote(newWidth);
					average.width(newWidth);
					// Use GoogleScript JSONP call to store rating data
                        tclWidget.$.getJSON(opts.scriptPath,{
                                                
							postID : idPost,
							rate : rate,
							action : 'rating'
						},
                            function(data) {
	                            if(!data.error)
								{
									if(opts.onSuccess) opts.onSuccess( data );      
								}
								else
								{
									if(opts.onError) opts.onError( data );
								}
							}
                                           
                        );
					/** ONLY FOR THE DEMO, YOU CAN REMOVE THIS CODE **/
                                        //	tclWidget.$('.datasSent p').html('<strong>idBox : </strong>'+idBox+'<br /><strong>rate : </strong>'+rate+'<br /><strong>action :</strong> rating');
					//	tclWidget.$('.serverResponse p').html('<strong>Loading...</strong>');
					/** END ONLY FOR THE DEMO **/
				}
			});

			function getNote(relativeX) {
				var noteBrut = parseFloat((relativeX*100/widthRatingContainer)*opts.rateMax/100);
				switch(opts.decimalLength) {
					case 1 :
						var note = Math.round(noteBrut*10)/10;
						break;
					case 2 :
						var note = Math.round(noteBrut*100)/100;
						break;
					case 3 :
						var note = Math.round(noteBrut*1000)/1000;
						break;
					default :
						var note = Math.round(noteBrut*1)/1;
				}
				return note;
			};

			function getStarWidth(){
				switch(opts.type) {
					case 'small' :
						starWidth = 12; // width of the picture small.png
						starHeight = 10; // height of the picture small.png
						bgPath = opts.smallStarsPath;
					break;
					default :
						starWidth = 23; // width of the picture stars.png
						starHeight = 20; // height of the picture stars.png
						bgPath = opts.bigStarsPath;
				}
			};

			function findRealLeft(obj) {
			  if( !obj ) return 0;
			  return obj.offsetLeft + findRealLeft( obj.offsetParent );
			};
				
		});

	}
})(tclWidget,jQuery);